import React, { useEffect, useState } from 'react'
import { Layout, Button, PageHeader, List, Modal, Row, Col, Descriptions, Divider, message } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import MyHeader from "../../view/Header";
import { get } from "../../util/get"
import { useLocation, useNavigate } from 'react-router-dom';
import EditOrderAddressModal from '../../components/EditOrderAddressModal';
import style from "./index.module.css"
import { post } from '../../util/post';
import OrderFoodItem from '../../components/orderFoodItem';
import AddAddressModal from '../../components/AddAddressModal';
const { Content, Footer } = Layout;
const { confirm } = Modal
/**
 * 购物车提交->提交表单页面
 * @returns Order component
 */
export default function Order() {
  const token = localStorage.getItem('TOKEN')
  const location = useLocation()
  const [listData, setListData] = useState([])
  const [info, setInfo] = useState([])
  const [address, setAddress] = useState('')
  const [total, setTotal] = useState(0);
  const [v, setV] = useState(false)
  const [addressList, setAddressList] = useState([]);
  const [orderToken, setOrderToken] = useState('');
  const [addV, setaddV] = useState(false);
  const [refresh, setRefresh] = useState(false);
  const navigate = useNavigate()
  const getAddressList = async () => {
    const res = await get('/user/address/list', token)
    const { code, page: { list, totalCount } } = res.data
    if (!code) {
      if (list.length > 0) return list;
      else confirm({
        title: '没有收货地址',
        icon: <ExclamationCircleOutlined />,
        content: '请填写收货地址',
        onOk() {
          setaddV(true)
        },
        onCancel() {
        }
      })
    }
  }
  useEffect(() => {
    const { orderItemVos, token, payPrice } = location.state
    const list = getAddressList()
    list.then(r => {
      const a = r.filter(item => item.cdefault === true)
      setAddress(a[0])
      setAddressList(r)
      setListData(orderItemVos)
      setTotal(payPrice)
      setOrderToken(token)
    })
  }, [location, refresh])

  useEffect(() => {
    get(`/shop/shop/info/${location.state.shopId}`, token).then(res => {
      setInfo(res.data.data)
    })
  }, [])
  const handlePay = async (orderSn) => {//处理用户支付
    const res = await get(`/order/alipayOrder?orderSn=${orderSn}`, token)
    const newWindow = window.open("","_self");
    newWindow.document.write(res.data);
    newWindow.focus();
}
  const payConfirm = (data)=>{
    console.log(data,'提交后的数据')
    confirm({
      title: '您现在要去支付吗',
      icon: <ExclamationCircleOutlined />,
      content: '请在15分钟内完成',
      onOk() {
        handlePay(data)
      },
      onCancel() {
        message.info('可以在“我的订单”中找到这次记录')
      }
    })
  }
  const submitOrder = async () => {
    const res = await post('/order/order/submit', {
      shopId: location.state.shopId,
      addressId: address.id,
      orderToken,
      payPrice: total
    }, token)
    const { code, msg,data:{order:{orderSn}} } = res.data
    if (code === 0) {
      message.success(msg)
      payConfirm(orderSn)
    }
    else message.error(msg)
  }
  const handleSubmit = () => {
    confirm({
      title: '确认提交',
      icon: <ExclamationCircleOutlined />,
      content: '请检查收货地址与商品信息无误。',
      onOk() {
        submitOrder()
      },

      onCancel() {
      },
    });
  }
  return (
    <Layout className="layout">
      <MyHeader type={1} />
      <Content
        className={style.content}
        style={{
          padding: '0 50px',
          background: '#f0f0f0'
        }}
      >
        <PageHeader
          style={{ 'background': 'white' }}
          className="site-page-header"
          onBack={() => navigate(-1)}
          title={'返回'}
        />
        <Descriptions
          className={style.shopInfo}
          title={
            <Row>
              <Col span={4}>
                <img alt='照片' width={200} height={200} src={info.image} />
              </Col>
              <Col span={16} className={style.title}>
                {info.name}
              </Col>
              <Col span={4}>
                <Button type='primary' onClick={() => setV(true)}>修改收货地址</Button>
              </Col>
            </Row>}>
          <Descriptions.Item label="收货人姓名">{address?.name}</Descriptions.Item>
          <Descriptions.Item label="联系号码">{address?.phone}</Descriptions.Item>
          <Descriptions.Item label="收货地址">{address?.address}</Descriptions.Item>
        </Descriptions>
        <List
          itemLayout="horizontal"
          dataSource={listData}
          className={style.foodlist}
          renderItem={(item) => {
            return (
              <OrderFoodItem size={128} data={item}></OrderFoodItem>
            )
          }
          }

        />
        <Divider>总计</Divider>
        <div className={style.price}>
          <div>
            <span>总金额</span>
            <span>¥{total}.00</span>
          </div>
          <div>
            <span>优惠</span>
            <span>¥0.00</span>
          </div>
          <div>
            <span>实际支付</span>
            <span>¥{total}.00</span>
          </div>
        </div>
        <div className={style.submitBox}>
          <Button className={style.submit} onClick={handleSubmit} type='primary'>提交</Button>
        </div>
        <AddAddressModal visible={addV} setVisible={setaddV} refresh={setRefresh}></AddAddressModal>
        <EditOrderAddressModal data={addressList} changeUse={setAddress} v={v} setV={setV} />
      </Content>
      <Footer
        style={{
          textAlign: 'center',
          background: "#001529",
          color: "white"
        }}
      >
        Ant Design ©2018 Created by Ant UED
      </Footer>
    </Layout>
  )
}
